﻿using Domain.Entity;
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys
{
    public class RolesJurisdictionRepository: IRolesJurisdictionRepository
    {
        private readonly MyDbContext myDbContext;

        public RolesJurisdictionRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        //查询
        public List<RolesJurisdiction> GetRolesJurisdiction(int rid)
        {
            return myDbContext.RolesJurisdiction.Where(s=>s.RolesID == rid).ToList();
        }

        //删除
        public async Task<bool> DeleteRolesJurisdictionAsync(int rid)
        {
            // 查找指定角色权限  
            var rolesJurisdiction = await myDbContext.RolesJurisdiction
                .Where(s => s.RolesID == rid)
                .ToListAsync(); // 使用异步加载  

            // 检查是否找到  
            if (rolesJurisdiction == null || !rolesJurisdiction.Any())
            {
                return false; // 或抛出一个自定义异常  
            }

            // 循环删除角色权限  
            foreach (var jurisdiction in rolesJurisdiction)
            {
                myDbContext.RolesJurisdiction.Remove(jurisdiction);
            }

            // 保存更改  
            int result = await myDbContext.SaveChangesAsync();

            return result > 0;
        }

        //新增
        public async Task<bool> AddRolesJurisdictionAsync(int rid, int jid)
        {
            RolesJurisdiction rolesJurisdiction=new RolesJurisdiction() { 
                RolesID = rid,
                JuriID = jid
            };

               // 将新角色权限添加到上下文中  
               await myDbContext.RolesJurisdiction.AddAsync(rolesJurisdiction);

            // 保存更改  
            int result = await myDbContext.SaveChangesAsync();

            return result > 0; // 返回是否成功添加  
        }
    }
}
